<?php

/**
 * @author 1054229380@qq.com
 * @createtime 2017-7-3
 * -------------------------------------
 * 文件上传处理类
 * -------------------------------------
 *
 */
class fileupload
{

    var $dir; //文件件存放目录
    var $time; //自定义文件上传时间
    var $allow_types; //允许上传附件类型
    var $field; //上传控件名称
    var $maxsize; //最大允许文件大小KB
    var $thumb_width; //缩略图宽度
    var $thumb_height; //缩略图高度
    var $new_width; //生成图宽度
    var $new_height; //生成图高度
    var $is_waterMarke; //生成水印
    var $watermark_file = 'assets/global/imgs/watermark.png'; //水印图片地址
    var $watermark_pos; //水印位置
    var $watermark_trans; //水印透明度
    var $img_url; //文件地址
    var $thumb_url; //缩图地址

    //初始化 $maxsize单位为KB

    function fileupload($allowtypes = 'jpg|png|gif', $maxsize = 1024, $field = 'Filedata', $time = '')
    {
        $this->allow_types = $allowtypes;
        $this->maxsize = $maxsize * 1024 * 2;
        $this->field = $field;
        $this->time = $time ? $time : time();
    }

    //图片缩略图设置，如果不生成缩略图则不用设置
    //$width : 缩略图宽度 , $height : 缩略图高度
    function set_thumb($width = 0, $height = 0)
    {
        $this->thumb_width = $width;
        $this->thumb_height = $height;
    }

    //生成图设置，如果改变原图则不用设置
    //$width : 图宽度 , $height :图高度
    function set_newpic($_width = 0, $_height = 0)
    {
        $this->new_width = $_width;
        $this->new_height = $_height;
    }

    //创建文件存放的目录
    function set_dir($basedir, $filedir = '')
    {
        date_default_timezone_set("Asia/Shanghai");
        $dir = $basedir;
        !is_dir($dir) && @mkdir($dir, 0777);
        if (!empty($filedir)) {
            $filedir = str_replace(array(
                '{y}',
                '{m}',
                '{d}',
                '{h}'
            ), array(
                date('Y', $this->time),
                date('m', $this->time),
                date('d', $this->time),
                date('H', $this->time)
            ), strtolower($filedir));
            $dirs = explode('/', $filedir);
            foreach ($dirs as $d) {
                !empty($d) && $dir .= $d . '/';
                !is_dir($dir) && @mkdir($dir, 0777);
            }
        }
        $this->dir = $dir;
    }

    //执行单个上传
    // flag= 0  上传成功
    // flag= 1  没有选择文件
    // flag= 2  文件类型不正确
    // flag= 3  文件超过规定大小
    function execute()
    {

        //e($_FILES);
        //print_r($_SERVER);
        //e($_POST);
        //exit();
        $altypes = $this->allow_types;
        $this->allow_types = explode('|', $this->allow_types);
        $files = array();
        $field = $this->field;
        //e($_FILES);
        //exit();
        if (!isset($_FILES[$field]['name'])) {
            $backArr['backType'] = "1";
            $backArr['uploadFileName'] = "";
            return $backArr;
        }

        $fileext = $this->fileext($_FILES[$field]['name']); //获取文件扩展名
        $_tmpUploadFileName = $_FILES[$field]['name'];
        $filename = date('i', $this->time) . date('s', $this->time) . mt_rand(1000, 9999) . '.' . $fileext; //生成文件名
        $filedir = $this->dir; //附件实际存放目录
        $filesize = $_FILES[$field]['size']; //文件大小
        //文件没上传
//        if ($filesize == "0" || $filesize == "") {
//			$backArr['backType']="1";
//			$backArr['uploadFileName']=$_tmpUploadFileName;
//			return $backArr;
//        }
        //文件格式不正确
        if (!in_array($fileext, $this->allow_types)) {
            $altypes = str_replace("|", ",", $altypes);
            $backArr['backType'] = "2";
            $backArr['uploadFileName'] = $_tmpUploadFileName;
            return $backArr;
        }
        //文件大小超出
        if ($filesize > $this->maxsize) {
            $maxsize = $this->maxsize / 1024;
            $backArr['backType'] = "3";
            $backArr['uploadFileName'] = $_tmpUploadFileName;
            return $backArr;
        }
        if (is_uploaded_file($_FILES[$field]['tmp_name'])) {
            move_uploaded_file($_FILES[$field]['tmp_name'], $filedir . $filename); //exit();
            $_tmpFileFullUrl = $filedir . $filename;
            $_tmpFileUrl = str_replace(APP_ROOT, "", $_tmpFileFullUrl);
            $this->_tmpFileUrl = $_tmpFileUrl;
            if ($this->new_width) { //如果设置，则生成新图片大小
                $_width = $this->new_width;
                $_height = $this->new_height;
                $this->img_url = $_tmpFileFullUrl;
                $this->create_pic(0, $_width, $_height);
                //$this->create_pic(1, 60,60);
            }
            @unlink($_FILES[$field]['tmp_name']);

            //生成水印
            if ($this->is_waterMarke == 1) {
                $this->watermark($_tmpFileFullUrl, $this->watermark_file, 3);
            }
            $backArr['backType'] = "4";
            $backArr['uploadFileName'] = $_tmpUploadFileName;
            return $backArr;
        }
    }

    //获取文件扩展名
    function fileext($filename)
    {
        return strtolower(substr(strrchr($filename, '.'), 1, 10));
    }

    //设置图片生成质量，大小,0,当前位置,1,新位置
    function create_pic($savelocation, $w = 0, $h = 0)
    {
        return $this->create_thumb($savelocation, $w, $h);
    }

    //创建缩略图
    function create_thumb($savelocation, $w, $h)
    {
        $sourcefile = $this->img_url;
        $thumb_file = $this->img_url;
        if ($savelocation == "1") { //新位置
            $t_width = $w;
            $t_height = $h;
            $imgquality = "100";
            $fileext = $this->fileext($thumb_file); //获取文件扩展名
            $thumb_file = str_replace("." . $fileext, "_$w-$h." . $fileext, $thumb_file);
        }
        if ($savelocation == "0") { //原位置生成
            //$t_width  = $this->new_width;
            //$t_height = $this->new_height;
            $t_width = $w;
            $t_height = $h;
            $imgquality = "100";
        }
        //echo $t_width.$t_height;
        if (!file_exists($sourcefile))
            return false;
        //echo "<br>".$sourcefile;
        $Phpaspx_info = getImageSize($sourcefile);
        //如果来源图像小于或等于缩略图则拷贝源图像作为缩略图
        if ($Phpaspx_info[0] <= $t_width && $Phpaspx_info[1] <= $t_height) {
            if (!@copy($sourcefile, $thumb_file)) {
                //echo $thumb_file."<br>";
                return false;
            }
            return true;
        }
        //按比例计算缩略图大小
        if ($Phpaspx_info[0] - $t_width > $Phpaspx_info[1] - $t_height) {
            $t_height = ($t_width / $Phpaspx_info[0]) * $Phpaspx_info[1];
        } else {
            $t_width = ($t_height / $Phpaspx_info[1]) * $Phpaspx_info[0];
        }
        //取得文件扩展名
        $fileext = $this->fileext($sourcefile);
        switch ($fileext) {
            case 'jpg':
                $Phpaspx_img = ImageCreateFromJPEG($sourcefile);
                break;

            case 'png':
                $Phpaspx_img = ImageCreateFromPNG($sourcefile);
                break;

            case 'gif':
                $Phpaspx_img = ImageCreateFromGIF($sourcefile);
                break;
        }
        //创建一个真彩色的缩略图像
        $thumb_img = @ImageCreateTrueColor($t_width, $t_height);
        @ImageCopyResized($thumb_img, $Phpaspx_img, 0, 0, 0, 0, $t_width, $t_height, $Phpaspx_info[0], $Phpaspx_info[1]);
        //生成缩略图
        switch ($fileext) {
            case 'jpg':
                ImageJPEG($thumb_img, $thumb_file, $imgquality);
                break;

            case 'gif':
                ImageGIF($thumb_img, $thumb_file, $imgquality);
                break;

            case 'png':
                ImagePNG($thumb_img, $thumb_file);
                break;
        }
        //销毁临时图像
        @ImageDestroy($Phpaspx_img);
        @ImageDestroy($thumb_img);
        $replstr = array(//  SITE_ROOT . "."
        );
        $thumb_file = str_replace($replstr, "", $thumb_file);
        $this->thumb_url = $thumb_file;
        //echo $thumb_file;
        return true;
    }

    //添加水印
    function create_watermark($sourcefile)
    {
        return;
    }

    function watermark($bigimg, $smallimg, $coord = 1)
    {
        //载入两张图片，并转成php识别的编码格式，
        //等同于 imagecreate 函数，只不过这里创建的不是一个空图片。
        $bi = getimagesize($bigimg);
        switch ($bi[2]) {
            case 1:
                $im1 = imagecreatefromgif($bigimg);
                break;
            case 2;
                $im1 = imagecreatefromjpeg($bigimg);
                break;
            case 3;
                $im1 = imagecreatefrompng($bigimg);
                break;
        }
        $si = getimagesize($smallimg);
        switch ($si[2]) {
            case 1:
                $im2 = imagecreatefromgif($smallimg);
                break;
            case 2;
                $im2 = imagecreatefromjpeg($smallimg);
                break;
            case 3;
                $im2 = imagecreatefrompng($smallimg);
                break;
        }
        // 创建水印--原理：复制小图到大图上。这里注意坐标值的计算
        switch ($coord) {
            case 1:
                imagecopy($im1, $im2, 0, 0, 0, 0, $si[0], $si[1]);
                break;
            case 2:
                imagecopy($im1, $im2, $bi[0] - $si[0], 0, 0, 0, $si[0], $si[1]);
                break;
            case 3:
                imagecopy($im1, $im2, $bi[0] - $si[0], $bi[1] - $si[1], 0, 0, $si[0], $si[1]);
                break;
            case 4:
                imagecopy($im1, $im2, 0, $bi[1] - $si[1], 0, 0, $si[0], $si[1]);
                break;
            case 5:
                imagecopy($im1, $im2, ($bi[0] - $si[0]) / 2, ($bi[1] - $si[1]) / 2, 0, 0, $si[0], $si[1]);
                break;
        }
        //根据后缀名生成不同格式的图片文件
        switch ($bi[2]) {
            case 1:
                imagegif($im1, $bigimg);
                break;
            case 2;
                imagejpeg($im1, $bigimg);
                break;
            case 3;
                imagepng($im1, $bigimg);
                break;
        }
        imagedestroy($im1);
    }

}

?>

